package cn.est.controller;


import cn.est.config.AlipayConfig;
import cn.est.constants.Constants;
import cn.est.pojo.MaintainOrder;
import cn.est.pojo.Model;
import cn.est.pojo.PayOrder;
import cn.est.service.MaintainOrderService;
import cn.est.service.ModelService;
import cn.est.service.PayOrderService;
import cn.est.utils.AlipayUtil;
import cn.est.utils.MathUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 订单支付信息 前端控制器
 * </p>
 *
 * @author qf
 * @since 2021-08-04
 */
@Slf4j
@RestController
@RequestMapping("/api/pay")
public class PayOrderController {

    private final AlipayUtil alipayUtil;
    private final AlipayConfig alipayConfig;
    private final MaintainOrderService maintainOrderService;
    private final ModelService modelService;
    private final PayOrderService payOrderService;

    public PayOrderController(AlipayUtil alipayUtil, AlipayConfig alipayConfig, MaintainOrderService maintainOrderService, ModelService modelService, PayOrderService payOrderService) {
        this.alipayUtil = alipayUtil;
        this.alipayConfig = alipayConfig;
        this.maintainOrderService = maintainOrderService;
        this.modelService = modelService;
        this.payOrderService = payOrderService;
    }

    @RequestMapping("aliPay")
    public String aliPay(String orderNo){
        log.info("orderNo-------->>> {}", orderNo);
        String result = "";
        // 1.modelName
        // 通过订单号，获取订单对象
        QueryWrapper<MaintainOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("orderNo", orderNo);
        MaintainOrder maintainOrder = maintainOrderService.getOne(wrapper);
        // 通过订单对象，获取商品id，通过商品id获取商品对象，对象中有商品名称
        Long modelId = maintainOrder.getModelId();
        Model model = modelService.getById(modelId);

        // 2.payNo
        StringBuffer buffer = new StringBuffer(orderNo);
        buffer.append(MathUtils.random());// 追加随机数
        String payNo = buffer.toString();

        // 3.价格
        BigDecimal subscription = maintainOrder.getSubscription();
        result = alipayUtil.aliPagePay(model.getModelName(),payNo,subscription.toString());

        // 先保存，但是没有阿里交易订单号
        PayOrder payOrder = new PayOrder(orderNo, payNo, maintainOrder.getUserId(), subscription, Constants.Order.PayType.DEPOSIT, Constants.Order.PayStaus.UN_PAY, Constants.Order.Channel.ALIPAY);
        payOrder.setCreatedUserId(maintainOrder.getUserId());
        payOrderService.save(payOrder);

        return result;
    }

    // 同步的方式，在支付成功页面倒计时之后支付宝会访问我们
    @GetMapping("aliPay/returnUrl")
    public String returnUrl(HttpServletRequest request) {
        String result = "";
        // 1.验签 - 有消息告诉我支付成功了，但是我不信，我应该获取这些消息，通过支付宝给我们的接口去验证而它
        // 支付宝表单内容
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 遍历这个map，获取值放到自己的map中
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String mapKey = entry.getKey();
            String mapValue = entry.getValue()[0]; // 支付宝给我们的value是一个String数组，但是只有一个元素有值
            map.put(mapKey, mapValue);
        }
        // 调用接口，得到返回值
        /*  boolean flag = false;
        try {
            // 验签，在这个过程中，可能会失败，1.因为维护，2.中文乱码(主要是因为subject 也就是商品名称)
            flag = Factory.Payment.Common().verifyNotify(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        */
        // 验签成功之后，应该修改支付订单表
        QueryWrapper<PayOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("orderNo", map.get("out_trade_no"));
        PayOrder one = payOrderService.getOne(wrapper);
        one.setAliTradeNo(map.get("trade_mo")); // 设置阿里的订单号
        one.setStatus(Constants.Order.PayStaus.SUCCESS); // 设置支付状态为成功
        payOrderService.updateById(one); // 修改

        // 2.如果正常的电商网站，应该修改库存，修改订单状态，我们二手兔维修的，只需要修改订单的状态，变成以付定金
        QueryWrapper<MaintainOrder> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("orderNo", map.get("out_trade_no"));
        MaintainOrder maintainOrder = maintainOrderService.getOne(wrapper2);
        maintainOrder.setStatus(Constants.Order.MaintainStatus.PAY_DEPOSIT); // 修改订单状态为支付定金
        maintainOrderService.updateById(maintainOrder);

        // 3.跳转页面
        result = alipayConfig.getSuccessUrl();

        return result;
    }
}

